﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text;
using System.Linq;
using System;

public static class SocketTool{

    public static IPAddress _localIp;

    public static string GetIpAddress()
    {
        string hostName = Dns.GetHostName();//得到主机名
        IPHostEntry localHost = Dns.GetHostByName(hostName);
        for (int i = 0; i < localHost.AddressList.Length; i++)
        {
            //从IP地址列表中筛选出IPv4类型的IP地址
            //AddressFamily.InterNetwork表示此IP为IPv4,
            //AddressFamily.InterNetworkV6表示此地址为IPv6类型
            if (localHost.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
            {
                _localIp = localHost.AddressList[i];
                //Debug.Log(localHost.AddressList[i].ToString());
            }
        }
        //IPAddress localAddress = localHost.AddressList[0];
        return _localIp.ToString();
    }

    public static byte[] TransMsg2Byte(string msgType,string content)
    {
        byte[] contentB = Encoding.Default.GetBytes(content);
        List<byte> list = new List<byte>();
        byte[] typeB=Encoding.Default.GetBytes(msgType);
        //string length = typeB.Length.ToString();//获取消息类字符串长度
        //length=length.PadLeft(4, '0');//补齐四位
        //byte[] flagB = Encoding.Default.GetBytes(length);
        byte[] flagB = BitConverter.GetBytes(typeB.Length);//转换成int32的字节数组（四位）

        list.AddRange(flagB);
        list.AddRange(typeB);
        list.AddRange(contentB);
        return list.ToArray();
    }

    public static TransMsg TransByte2Msg(byte[] data)
    {
       int typeLength =BitConverter.ToInt32(data, 0);
       //Debug.Log(typeLength) ;
        string type = Encoding.Default.GetString(data.Skip(4).Take(typeLength).ToArray());
        //Debug.Log(type);
        string msgStr = Encoding.Default.GetString(data.Skip((4 + typeLength)).Take(data.Length).ToArray());
        //Debug.Log(msgStr);
        return new TransMsg(type, msgStr);
    }
}
